package com.handyshop.mall.basic.core.exception;


import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.handyshop.mall.basic.core.constants.ErrorEnum;
import com.handyshop.mall.basic.core.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 授权拒绝处理器，覆盖默认的OAuth2AccessDeniedHandler
 * 包装失败信息到PigDeniedException
 *
 * @author hs
 * @date 2020/11/13 11:51
 */
@Slf4j
@Component
public class AuthAccessDeniedHandler extends OAuth2AccessDeniedHandler {

    /**
     * 授权拒绝处理，使用R包装
     *
     * @param request       request
     * @param response      response
     * @param authException authException
     * @throws IOException      IOException
     * @throws ServletException ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpStatus.HTTP_FORBIDDEN);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(JSONUtil.parse(ResultVo.failure(ErrorEnum.AUTHORIZATION_FAILURE)).toString());
    }

    @Override
    public void setExceptionTranslator(WebResponseExceptionTranslator<?> exceptionTranslator) {
        super.setExceptionTranslator(exceptionTranslator);
    }

}
